require('normalize.css/normalize.css');
require('styles/App.css');

import React from 'react';
var ReactDOM = require('react-dom');
//获取图片信息
var imageDatas = require('../data/imageDatas.json')

//给图片加上url路径
imageDatas = (function getImageURL(imageDataArr){
	
	for (var i=0, j = imageDataArr.length; i < j; i++) {
		var singleImageData = imageDataArr[i];

		singleImageData.imageURL = require('../images/' + singleImageData.fileName);

		imageDataArr[i] = singleImageData;
	}

	return imageDataArr;
})(imageDatas);


function getRangeRandom(low, high){
	return Math.ceil(Math.random() * (high - low) + low);
}

function get30DegRandom(){

	return ((Math.random() > 0.5 ? "" : "-") + Math.ceil(Math.random() * 30));
}



var ImgFigure = React.createClass({

	handleClick: function(e){
		if (this.props.arrange.isCenter) {
			this.props.inverse();
		} else{
			this.props.center();
		}
		

		e.stopPropagation();
		e.preventDefault();
	},

	render: function(){
		
		var styleObj = {};

		if (this.props.arrange.pos) {

			styleObj = this.props.arrange.pos;
		}

		if (this.props.arrange.isCenter) {
			styleObj.zIndex = 11;
		}

		if (this.props.arrange.rotate) {
			(['-moz-', '-ms-', '-webkit-', '']).forEach(function(){

				styleObj['transform'] = 'rotate(' + this.props.arrange.rotate + 'deg)'

			}.bind(this));
		}


		var imgFigureClassName = 'img-figure';
		imgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : '';
		return(
			<figure className={imgFigureClassName} style={styleObj} onClick = {this.handleClick}>
				<img src={this.props.data.imageURL} alt={this.props.data.title} />
				<figcation className="img-title">
					<h2>{this.props.data.title}</h2>
					<div className = "img-back" onClick = {this.handleClick}>
						<p> {this.props.data.desc} </p>
					</div>
				</figcation>
			</figure>
		);
	}
});

var ControllerUnit = React.createClass({
	handleClick: function(e){

		if (this.props.arrange.isCenter) {
			this.props.inverse()
		}else{
			this.props.center();
		}

		e.preventDefault();
		e.stopPropagation();
	},


	render: function(){
		
		var controlelrUnitClassName = 'controller-unit';
	    // 如果对应的是居中的图片，显示控制按钮的居中态
	    if (this.props.arrange.isCenter) {
	      controlelrUnitClassName += ' is-center';

	      // 如果同时对应的是翻转图片， 显示控制按钮的翻转态
	      if (this.props.arrange.isInverse) {
	        controlelrUnitClassName += ' is-inverse';
	      }
	    }

		return(
			<span className={controlelrUnitClassName} onClick={this.handleClick}></span>
		)
	}
});

var  AppComponent  = React.createClass({
	Constant: {
      centerPos: {
        left: 0,
        right: 0
      },
      hPosRange: {   // 水平方向的取值范围
        leftSecX: [0, 0],
        rightSecX: [0, 0],
        y: [0, 0]
      },
      vPosRange: {    // 垂直方向的取值范围
        x: [0, 0],
        topY: [0, 0]
      }
    },
	

	getInitialState: function(){
		return{
			imagsArrangArr:[]
		};

	},

	inverse: function(index){
		return function(){
			
			var imgsArrangeArr = this.state.imagsArrangArr;

			imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;

			this.setState({
				imagsArrangArr:imgsArrangeArr
			})
		}.bind(this);
	},

	center:function(index){
		return function(){
			this.rearrange(index);
		}.bind(this);
	},

	rearrange: function(centerIndex){
		var imgsArrangeArr = this.state.imagsArrangArr,
      		Constant = this.Constant,
      		centerPos = Constant.centerPos,
      		hPosRange = Constant.hPosRange,
      		vPosRange = Constant.vPosRange,
      		hPosRangeLeftSecX = hPosRange.leftSecX,
      		hPosRangeRightSecX = hPosRange.rightSecX,
      		hPosRangeY = hPosRange.y,
      		vPosRangeTopY = vPosRange.topY,
      		vPosRangeX = vPosRange.x,

      		imgsArrangeTopArr = [],
      		topImgNum = Math.floor(Math.random() * 2),    // 取一个或者不取
      		topImgSpliceIndex = 0,

      		imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1);

		imgsArrangeCenterArr[0] = {
			pos : centerPos,
			rotate : 0,
			isCenter : true
		};

		//取出要布局上策的图片的状态信息
		topImgSpliceIndex = Math.floor(Math.random() * (imgsArrangeArr.length - topImgNum));
		//topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum));

		imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex,topImgNum);

		imgsArrangeTopArr.forEach(function(value,index){

			imgsArrangeTopArr[index] = {
				pos: {
					top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]),
					left: getRangeRandom(vPosRangeX[0], vPosRangeX[1])
				},
				rotate: get30DegRandom(),
				isCenter: false
			}


		});

		
		// 布局左右两侧的图片
		for (var i=0, j= imgsArrangeArr.length, k = j /2; i < j; i++) {
			
			var hPosRangeLORX = null;

			// 前半部分布局左边， 右半部分布局右边
			if (i < k) {
				hPosRangeLORX = hPosRangeLeftSecX;
			}else {
				hPosRangeLORX = hPosRangeRightSecX;
			}

			imgsArrangeArr[i] = {
				pos: {
					top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]),
					left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1])
				},
				rotate: get30DegRandom(),
				isCenter:false
			}
		}


		if (imgsArrangeTopArr && imgsArrangeTopArr[0]) {
			imgsArrangeArr.splice(topImgNum, 0 , imgsArrangeTopArr[0]);
		}

		imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]);

		this.setState({
			imagsArrangArr: imgsArrangeArr
		});
	},


	componentDidMount : function(){
		
		 // 首先拿到舞台的大小
    	var stageDOM = ReactDOM.findDOMNode(this.refs.stage),
      		stageW = stageDOM.scrollWidth,
      		stageH = stageDOM.scrollHeight,
      		halfStageW = Math.ceil(stageW / 2),
      		halfStageH = Math.ceil(stageH / 2);

    	// 拿到一个imageFigure的大小
	    var imgFigureDOM = ReactDOM.findDOMNode(this.refs.imgFigure0),
	      	imgW = imgFigureDOM.scrollWidth,
	      	imgH = imgFigureDOM.scrollHeight,
	      	halfImgW = Math.ceil(imgW / 2),
	      	halfImgH = Math.ceil(imgH / 2);

	    // 计算中心图片的位置点
	    this.Constant.centerPos = {
	      	left: halfStageW - halfImgW,
	      	top: halfStageH - halfImgH
	    };

	    // 计算左侧，右侧区域图片排布位置的取值范围
	    this.Constant.hPosRange.leftSecX[0] = -halfImgW;
	    this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3;
	    this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW;
	    this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW;
	    this.Constant.hPosRange.y[0] = -halfImgH;
	    this.Constant.hPosRange.y[1] = stageH - halfImgH;

	    // 计算上侧区域图片排布位置的取值范围
	    this.Constant.vPosRange.topY[0] = -halfImgH;
	    this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
	    this.Constant.vPosRange.x[0] = halfStageW - imgW;
	    this.Constant.vPosRange.x[1] = halfStageW;

	    var imgsArrangeArr = this.state.imagsArrangArr;

	    this.rearrange(getRangeRandom(0,imgsArrangeArr.length));
	},

	render() {

	  	var controllerUnits = [],
				imagFigures = [];

		imageDatas.forEach(function(value,index){

			if (!this.state.imagsArrangArr[index]) {
				this.state.imagsArrangArr[index] = {
					pos:{
						left:0,
						top:0
					},
					rotate:0,
					isInverse: false
				}
			}


			imagFigures.push(<ImgFigure data = {value} key={index} ref={'imgFigure' + index} arrange={this.state.imagsArrangArr[index]} inverse = {this.inverse(index)} center = {this.center(index)}/>);
			controllerUnits.push(<ControllerUnit arrange={this.state.imagsArrangArr[index]} key={index} inverse = {this.inverse(index)} center = {this.center(index)}/>)
		}.bind(this));

	    return (
	     	<section className="stage" ref="stage">
	     		<section className="img-sec">
	     			{imagFigures}
	     		</section>
	     		<nav className="controller-nav">
	     			{controllerUnits}
	     		</nav>
	     	</section>
	    );
	}
});

AppComponent.defaultProps = {
};

export default AppComponent;
